import React, {Component} from 'react';
import {View, Text, Button, Image, TouchableOpacity, StyleSheet, PermissionsAndroid, TextInput} from 'react-native';
import {StackActions, NavigationActions} from 'react-navigation';
import {Header, Overlay} from 'react-native-elements';
import {MapView, Marker, MultiPoint} from 'react-native-amap3d';
import RNLocation from 'react-native-location';
import axios from 'axios';
import Geolocation from '@react-native-community/geolocation';
import {serverUrl} from '../../app';


export default class HomeScreen extends Component {
    static navigationOptions = ({navigation}) => {
        return {
            title: '地图',
            headerTitleStyle: {
                textAlign: 'center',
                flex: 1,
            },
            headerLeft: (
                <TouchableOpacity onPress={() => {
                    navigation.push('logScreen', {id: 'string2'});
                }}>
                    <Image
                        source={require('../../img/center.png')}
                        style={{width: 30, height: 30}}
                    />
                </TouchableOpacity>
            ),
            headerRight: (
                <TouchableOpacity onPress={() => {
                    navigation.push('ScanPage');
                    // navigation.push('cameraPage');
                }}>
                    <Image
                        source={require('../../img/scan.png')}
                        style={{width: 30, height: 30}}
                    />
                </TouchableOpacity>
            ),
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            latitude: 0,
            longitude: 0,
            selectedTree: '',
            treeList: [],
            overlayVisible: false,
        };
        this.getAllTree = this.getAllTree.bind(this);
        this.createTreeMarkers = this.createTreeMarkers.bind(this);
        this.checkPermission = this.checkPermission.bind(this);
        this.initSelectedTree = this.initSelectedTree.bind(this);
    }

// 获取坐标
    getLocation() {
        Geolocation.getCurrentPosition(location => {
            this.setState({longitude: location.coords.longitude, latitude: location.coords.latitude});
            this.mapView.animateTo({
                tilt: 0,
                rotation: 0,
                zoomLevel: 16,
                coordinate: {
                    latitude: location.coords.latitude,
                    longitude: location.coords.longitude,
                },
            });
        }, error => {
            if (error.code == 2) {
                alert('定位失败，请查看手机是否开启GPS定位服务');
            } else if (error.code == 3) {
                alert('定位超时，请尝试重新获取定位');
            } else {
                alert('定位失败，' + error.message);
            }
        }, {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 10000,
        });
    }

// 检查权限
    async checkPermission() {
        if (Platform.OS == 'ios') {
            this.getLocation();
        } else {
            const permissions = [
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            ];
            const granteds = await PermissionsAndroid.requestMultiple(permissions);
            if (granteds['android.permission.ACCESS_FINE_LOCATION'] == 'granted') {
                this.getLocation();
            } else {
                alert('定位权限被禁止');
            }
        }
    }

    // 获取所有果树
    getAllTree() {
        axios.get(serverUrl + '/getAllTree')
            .then((response) => {
                this.setState({treeList: []});
                setTimeout(() => {
                    this.setState({
                        treeList: response.data,
                    });
                }, 1000);
                // this.forceUpdate();
            })
            .catch(function (error) {
                console.log(error);
                alert(error);
            });
    }

    initSelectedTree() {
        let treeName = this.props.navigation.getParam('treeName', '');
        if (treeName != '') {
            axios.get(serverUrl + '/getTreeByName/{name}?name=' + treeName)
                .then((response) => {
                    if (response.data == '') {
                        this.setState({
                            selectedTree: {
                                'description': '',
                                'geometry': this.state.latitude + ',' + this.state.longitude,
                                'name': treeName,
                                'production': '',
                                'state': 1,
                            },
                        });
                    } else {
                        this.setState({
                            selectedTree: response.data,
                        });
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    alert(error);
                });
        }
    }

    createTreeMarkers(treeList) {
        let arr = [];
        for (let i = 0; i < treeList.length; i++) {
            let name = treeList[i].name;
            let pos = treeList[i].geometry.split(',');
            arr.push(
                <Marker
                    draggable
                    key={treeList[i].id}
                    title={name}
                    onPress={(event) => {
                        console.log(event.nativeEvent);
                    }}
                    onDragEnd={({nativeEvent}) =>
                        console.log(`${nativeEvent.latitude}, ${nativeEvent.longitude}`)
                    }
                    coordinate={{
                        latitude: parseFloat(pos[0]),
                        longitude: parseFloat(pos[1]),
                    }}
                />);
        }
        return (
            <View style={{flex: 1}}>
                {<View>{arr}</View>}
            </View>
        );
    }

    createTreeMarkers2(treeList) {
        let arr = [];
        for (let i = 0; i < treeList.length; i++) {
            let pos = treeList[i].geometry.split(',');
            arr.push({
                latitude: parseFloat(pos[0]),
                longitude: parseFloat(pos[1]),
            });
        }
        return arr;
    }

    // 选择果树
    handleMarkerClick(coor) {
        let treeList = this.state.treeList;
        for (let item in treeList) {
            let geo = treeList[item].geometry.split(',');
            let dis = Math.abs(coor.latitude - parseFloat(geo[0])) + Math.abs(coor.longitude - parseFloat(geo[1]));
            if (dis < 0.0001) {
                this.setState({selectedTree: treeList[item]});
            }
        }
    }

    // 更新保存果树信息
    handleSaveButtonClick() {
        axios.post(serverUrl + '/saveTree', this.state.selectedTree)
            .then((response) => {
                alert('保存成功');
                this.getAllTree();
                this.setState({
                    selectedTree: response.data,
                });
            })
            .catch(function (error) {
                console.log(error);
                alert(error);
            });
    }

    componentDidMount() {
        this.checkPermission();
        this.getAllTree();
        this.initSelectedTree();
    }

    render() {
        const {navigate} = this.props.navigation;
        return (
            <View style={{flex: 1}}>
                <View style={{flex: 1}}>
                    <MapView style={styles.MapView}
                             mapType='satellite'
                             ref={ref => this.mapView = ref}
                    >
                        <Marker
                            active
                            color='red'
                            title='我'
                            coordinate={this.state}
                        />
                        {
                            this.state.treeList.length > 0 && (
                                <MultiPoint
                                    image='point'
                                    points={this.createTreeMarkers2(this.state.treeList)}
                                    onItemPress={index => this.handleMarkerClick(index)}
                                />
                            )
                        }
                        {
                            this.state.selectedTree != '' && (
                                <Marker
                                    active
                                    draggable
                                    title={this.state.selectedTree.name}
                                    color='green'
                                    onDragEnd={({nativeEvent}) => {
                                        let data = Object.assign({}, this.state.selectedTree, {geometry: `${nativeEvent.latitude.toFixed(4)}, ${nativeEvent.longitude.toFixed(4)}`});
                                        this.setState({selectedTree: data});
                                        // console.log(this.state.selectedTree.geometry);
                                    }
                                    }
                                    coordinate={{
                                        latitude: parseFloat(this.state.selectedTree.geometry.split(',')[0]),
                                        longitude: parseFloat(this.state.selectedTree.geometry.split(',')[1]),
                                    }}
                                />
                            )
                        }
                    </MapView>
                </View>
                {
                    this.state.selectedTree != '' && (
                        <View style={{flex: 2}}>
                            {
                                this.state.selectedTree != '' && (
                                    <View style={{marginLeft: 10, marginRight: 10}}>
                                        <View>
                                            <Text>名称：</Text>
                                            <TextInput
                                                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                                                value={this.state.selectedTree.name}
                                            />
                                        </View>
                                        <View>
                                            <Text>产量：</Text>
                                            <TextInput
                                                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                                                value={this.state.selectedTree.production}
                                                onChangeText={(text) => {
                                                    let data = Object.assign({}, this.state.selectedTree, {production: text});
                                                    this.setState({selectedTree: data});
                                                }}
                                            />
                                        </View>
                                        <View>
                                            <Text>描述：</Text>
                                            <TextInput
                                                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                                                value={this.state.selectedTree.description}
                                                onChangeText={(text) => {
                                                    let data = Object.assign({}, this.state.selectedTree, {description: text});
                                                    this.setState({selectedTree: data});
                                                }}
                                            />
                                        </View>
                                        <View>
                                            <Text>位置：</Text>
                                            <TextInput
                                                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                                                value={this.state.selectedTree.geometry}
                                                onChangeText={(text) => {
                                                    let data = Object.assign({}, this.state.selectedTree, {geometry: text});
                                                    this.setState({selectedTree: data});
                                                }}
                                            />
                                        </View>
                                        <View style={{flexDirection: 'row', margin: 10}}>
                                            <View style={{flex: 1, margin: 10}}>
                                                <Button title="保存" onPress={this.handleSaveButtonClick.bind(this)}/>
                                            </View>
                                            <View style={{flex: 1, margin: 10}}>
                                                <Button title="日志"
                                                        onPress={() => {
                                                            this.props.navigation.push('logScreen', {treeName: this.state.selectedTree.name});
                                                        }}
                                                />
                                            </View>
                                        </View>
                                    </View>
                                )
                            }
                        </View>)
                }

            </View>
        );
    }
}

const styles = StyleSheet.create({
    Header: {
        top: 0,
    },
    MapView: {
        flex: 1,
    },
});

